package com.hk.admin.spring.security;

import com.hk.admin.common.constant.GlobalConstants;
import com.hk.admin.common.constant.GlobalEnum;
import com.hk.admin.common.constant.system.UserEnum;
import com.hk.admin.common.model.system.UserModel;
import com.hk.admin.module.system.dao.UserRepository;
import com.hk.admin.module.system.service.MenuService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * <br>
 * <b>功能：</b>spring security 鉴权，重写loadUserByUsername方法，通过帐号获取帐号id、码、是否可用等信息<br>
 * <b>作者：</b>Pan.ShiJu<br>
 * <b>日期：</b>2017/10/4 23:27<br>
 */
public class CustomUserDetailsService implements UserDetailsService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private UserRepository systemUserRepository;
    @Autowired
    private MenuService menuService;

    /**
     * 查询登录信息是否正确
     *
     * @param userName
     * @return
     */
    @Override
    @Transactional
    public UserDetails loadUserByUsername(String userName) {
        logger.debug("--------------系统登录鉴权开始---------------");
        UserModel user = systemUserRepository.findByPhoneNumberAndDeleted(userName, GlobalEnum.DELETED.NO.getKey());
        if (user == null) {
            throw new UsernameNotFoundException("系统中不存在该用户。");
        }
        // 设置系统帐号类型
        Set<GrantedAuthority> authSet = new HashSet<>();
        GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(UserEnum.ACCOUNT_TYPE.getValueByKey(user.getAccountType()));
        authSet.add(grantedAuthority);

        // 当前用户的所有菜单url

        UserDetail userDetail = new UserDetail(user, authSet);
        List<String> menus = menuService.getMenuActionList(user);
        List<String[]> pathVariableArray = getPathVariable(menus);
        userDetail.setPathInvariable(menus);
        userDetail.setPathVariable(pathVariableArray);
        logger.debug("--------------系统登录鉴权结束---------------");
        return userDetail;
    }

    private List<String[]> getPathVariable(List<String> menus) {
        List<String> pathVariable = new ArrayList<>();
        for (int i = 0; i < menus.size(); i++) {
            if (menus.get(i).contains(GlobalConstants.OPEN_BRACE) && menus.get(i).contains(GlobalConstants.CLOSE_BRACE)) {
                pathVariable.add(menus.get(i));
                menus.remove(i);
                i--;
            }
        }
        List<String[]> pathVariableArray = new ArrayList<>();
        for (String path : pathVariable) {
            if (path.startsWith(GlobalConstants.LEFT_SLASH)) {
                path = path.replaceFirst(GlobalConstants.LEFT_SLASH, GlobalConstants.EMPTY_STRING);
            }
            pathVariableArray.add(path.split(GlobalConstants.LEFT_SLASH));
        }
        return pathVariableArray;
    }

}
